import React, { useState, useEffect } from 'react';
import * as XLSX from 'xlsx';
import dayjs from 'dayjs';
import JSZip from 'jszip';
import flowerIcon from './imgs/flowerIcon.png';
import { Button, Upload, Space, message, DatePicker } from 'antd';
import type { DatePickerProps } from 'antd';
import html2canvas from 'html2canvas';
import { UploadOutlined } from '@ant-design/icons';
import yuzhou from './imgs/yuzhou.png';
import yuzhou1 from './imgs/yuzhou1.png';
import yuzhou2 from './imgs/yuzhou2.png';
import yuzhou3 from './imgs/yuzhou3.png';
import yuzhou4 from './imgs/yuzhou4.png';
import yuzhou5 from './imgs/yuzhou5.png';
import yuzhou6 from './imgs/yuzhou6.png';

import style from './index.scss';
function getRandomIcon() {
  const icons = [yuzhou, yuzhou1, yuzhou2, yuzhou3, yuzhou4, yuzhou5, yuzhou6];
  const randomIndex = Math.floor(Math.random() * icons.length); // 生成0到5之间的随机整数
  return icons[randomIndex]; // 直接返回正确的数组项
}

export default function CosmicSoundTransmission() {
  const [data, setData] = useState<String[][]>([]);
  const [loading, setLoading] = useState(false);
  const [time, setTime] = useState<string>();

  useEffect(() => {
    let time = `${dayjs().format('M.D')} 传讯`;
    setTime(time);
  }, []);
  const beforeUpload = (file: File) => {
    try {
      console.log(file, 'fff');
      const reader = new FileReader();
      reader.onload = (e) => {
        const binaryData = e.target.result;

        // 解析Excel
        const workbook = XLSX.read(binaryData, { type: 'binary' });

        // 获取第一个工作表
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];

        // 转换为JSON
        const jsonData =
          XLSX.utils.sheet_to_json(worksheet, {
            header: 1, // 使用数组格式
            defval: '', // 空单元格默认值
            blankrows: false, // 保留空行
          }) || [];
        console.log(jsonData,'jsonData');
        jsonData.shift();
        setData(jsonData as any);
      };
      reader.readAsBinaryString(file);
      return false;
    } catch (error) {
      message.error('发生错误了,请刷新页面重新上传模版');
      return false;
    }
  };
  const downloadImg = async () => {
    try {
      if (data?.length === 0) {
        message.error('请上传模版');
        return;
      }
      const sourceMterialList = document.getElementById('source_mterial_list');
      if (!sourceMterialList) return;
      if (!time) {
        message.success('请选择时间');
        return;
      }
      message.info('正在生成图片，请稍后...');
      setLoading(true);
      const children = sourceMterialList.childNodes;
      const zip = new JSZip();

      // 1. 转换所有DOM元素为图片并收集Promise
      const imagePromises = Array.from(children).map(
        async (item: any, index) => {
          try {
            const canvas = await html2canvas(item, {
              allowTaint: true,
              useCORS: true,
              scale: 10, // 提高分辨率
            });

            // 将Canvas转换为Blob
            return new Promise<Blob | null>((resolve) => {
              canvas.toBlob((blob) => {
                resolve(blob);
              }, 'image/png');
            });
          } catch (error) {
            console.error(`Error converting item ${index}:`, error);
            return null;
          }
        }
      );

      try {
        // 2. 等待所有图片生成完成
        const blobs = await Promise.all(imagePromises);

        // 3. 将有效Blob添加到ZIP
        blobs.forEach((blob, index) => {
          if (blob) {
            zip.file(`image_${index + 1}.png`, blob);
          }
        });

        // 4. 生成ZIP文件并触发下载
        const content = await zip.generateAsync({ type: 'blob' });
        const url = URL.createObjectURL(content);

        const a = document.createElement('a');
        a.href = url;
        a.download = 'images.zip';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        setLoading(false);
      } catch (error) {
        console.error('Error generating ZIP:', error);
      }
    } catch (error) {
      message.error('发生错误了,请刷新页面重新上传模版');
    }
  };

  const onChange: DatePickerProps['onChange'] = (date, dateString) => {
    let time = `${dayjs(date).format('M.D')} 传讯`;
    console.log(time, 'ttt');

    setTime(time);
  };
  return (
    <div className={style.c_s_transmission_wrapper}>
      <Space>
        <Upload beforeUpload={beforeUpload}>
          <Button type="primary" icon={<UploadOutlined />} loading={loading}>
            上传Excel
          </Button>
        </Upload>
        <Button onClick={downloadImg} type="primary" loading={loading}>
          下载
        </Button>
      </Space>
      <div className={style.source_mterial_list} id="source_mterial_list">
        {data?.map((item, index) => {
          const icon = getRandomIcon();
          const nweItemData = item?.filter((item, i) => item && i !== 0);
          return (
            <div
              className={style.source_mterial_item}
              key={index}
              id={`id_${index}`}
            >
              <div className={style.source_mterial_text_content}>
                {nweItemData?.map((subItem,index) => {
                  return (
                    <div className={style.source_mterial_text_item}>
                      {/* <div className={style.source_mterial_item_icon}>
                        <img src={icon} alt="" />
                      </div> */}
                      <div className={style.source_mterial_item_text}>
                        { index + 1} . {`${subItem.trim()}`}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
